package top.jsjkxyjs.blackbox.ws;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import top.jsjkxyjs.blackbox.entity.Devbind;
import top.jsjkxyjs.blackbox.entity.Event;
import top.jsjkxyjs.blackbox.entity.Exclude;
import top.jsjkxyjs.blackbox.entity.User;
import top.jsjkxyjs.blackbox.service.*;
import top.jsjkxyjs.blackbox.utils.Msg;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ServerEndpoint(value = "/Events", configurator = MyEndpointConfigure.class)
@Component
public class EventDataEndPoint {
	public static EventService eventService;
	public static UserService userService;
	public static DevBindService devBindService;
	public static ExcludeService excludeService;
	public static CarTypeService carTypeService;
	private HttpSession httpSession;

	@OnOpen
	public void onOpen(Session session, EndpointConfig config) throws IOException, InterruptedException {
		httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
	}

	@OnMessage
	public void onMessage(Session session, String massage) throws IOException, InterruptedException {
		while (true) {
			List data = new ArrayList<>();
			List<Event> events = eventService.getAllEvents();
			for (Event event : events) {
				Devbind devbind = devBindService.getUserByIot(event.getDevId());
				User user = userService.getUserByUserId(devbind.getUserId());
				Exclude exclude = excludeService.getExcludeByEvent(event.getId());
				String carTypeByCarId = carTypeService.getCarTypeByCarId(devbind.getCarId());
				Map map = new HashMap<>();
				map.put("id", event.getId());
				map.put("userName", user.getUserName());
				map.put("type", event.getType());
				map.put("startTime", exclude.getStartTime());
				map.put("phone", user.getPhone());
				map.put("emergencyPhone", user.getEmergencyPhone());
				map.put("carType", carTypeByCarId);
				data.add(map);
			}
			ObjectMapper mapper = new ObjectMapper();
			session.getBasicRemote().sendText(mapper.writeValueAsString(Msg.success(data, events.size())));
			Thread.sleep(1000);
		}
	}

	@OnClose
	public void onClose() {
	}
}
